<template>
  <div>
    <el-form
      :inline="true"
      ref="form"
      :rules="formRules"
      :model="form"
      label-width="120px"
      size="small"
    >
      <el-form-item label="名称:" prop="name">
        <el-input v-model="form.name" class="w200"></el-input>
      </el-form-item>
      <el-form-item label="客户:">
        <div class="w300">
          <v-autocomplete
            :autoStatus="false"
            :autoVal="form.client_name"
            :autoId="form.client_id"
            ftype="text"
            v-on:selected="onSelClient"
            autoApi="client.get_list"
            :autoParm="{pagesize:200}"
            fname="name"
            fkey="id"
          ></v-autocomplete>
        </div>
      </el-form-item>
      <el-form-item label="分组:">
        <div class="w200">
          <v-autocomplete
            :autoStatus="false"
            autoVal="请选择分组"
            ftype="text"
            v-on:selected="onSelGroup"
            autoApi="flow_img.get_select_list"
            :autoParm="{}"
            fname="name"
            fkey="id"
          ></v-autocomplete>
        </div>
      </el-form-item>
      <el-form-item label="备注:">
        <el-input placeholder="请输入内容" v-model="form.bz" class="w300"></el-input>
      </el-form-item>
      <div class="dis10"></div>
      <div class="edit-graph-box">
        <h1>
          <span class="title">图形端口</span>
        </h1>
        <div class="dis20"></div>
        <div class="sel-graph-box">
          <div class="selected-box">
            <template v-if="chooseParseList.length > 0">
              <div class="select-list-box">
                <table class="table table-list">
                  <colgroup>
                    <col />
                    <col width="70px" />
                  </colgroup>
                  <tbody>
                    <tr v-for="(item ,index) in chooseParseList" :key="index">
                      <td>
                        
                        
                          <div
                            style="cursor:pointer"
                            slot="reference"
                            class="font-black f12"
                          > <el-tag
                          type="primary"
                          size="mini"
                          v-if="item['port_id'].indexOf(',') > 0" effect="dark"
                        >合</el-tag>
                             &nbsp;{{item.title}}
                            <div class="dis5"></div>     
                              
                            <div
                              v-for="(n, i) in item.node_ids"
                              :key="i"  class="node-tag">
                             <el-popover
                              placement="right"
                              width="530"
                              trigger="click"
                              position="left-start"
                              @show="showimg(n)"
                            > <img :src="imgsrc" alt="流量图" v-if="imgsrc" /><span v-else class="font-gray2 f12">处理中, 请稍后...</span> <span  slot="reference"><span class="font-gray2">N</span>{{ n.node_id }}</span></el-popover>
                            </div>                            
                          </div>
                        
                      </td>
                      <td>
                        <el-button
                          icon="el-icon-close"
                          @click.stop="delParseChoose(index)"
                          circle
                          size="mini"
                        ></el-button>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
              <div class="vbtns">
                <el-button style="margin-left:0" size="mini" disabled>已选: {{ chooseParseList.length }} 端口</el-button>
                <el-button size="mini" @click.stop="chooseList=[];chooseParseList=[]" type="default">清除</el-button>
              </div>
            </template>
            <div v-else style="padding: 180px 0; text-align:center;" colspan="2" class="tc">
              <span class="f18 font-gray2">请选择端口</span>
            </div>
          </div>
          <div class="unselect-box">
            <div class="filter-box">
              <span class="inblock" style="width: 200px;">
                <v-autocomplete
                  :autoStatus="false"
                  :autoVal="emptyNode"
                  autoId
                  ftype="text"
                  v-on:selected="onSelNode"
                  autoApi="idc_node.get_select_list"
                  :autoParm="{'cate': 'cacti'}"
                  fname="name"
                  fkey="id"
                ></v-autocomplete>
              </span>
              <span class="inblock" style="width: 300px;">
                <v-autocomplete
                  :autoStatus="false"
                  :autoVal="emptyHost"
                  autoId
                  ftype="text"
                  v-on:selected="onSelHost"
                  autoApi="cacti.get_host"
                  :autoParm="autoHostParams"
                  fname="description"
                  fkey="host_id"
                ></v-autocomplete>
              </span>
              <el-input
                trigger-on-focus
                clearable
                size="small"
                placeholder="请输入内容"
                v-model="keyword"
                class="input-with-select"
                style="width: 250px"
              >
                <el-button slot="append" icon="el-icon-search" @click.stop="searchHost"></el-button>
              </el-input>
            </div>
            <div class="unselect-list-box">
              <div class="left-list" :style="(pendingList.length > 0 ? 'right:38%' : '')">
                <v-list
                  api="cacti.get_port"
                  ref="unselectlist"
                  cols="30,0,60"
                  :params="paramsList"
                  :hideTool="true"
                >
                  <template slot="search"></template>
                  <template slot="head" slot-scope="props">
                    <thead>
                      <tr>
                        <th class="c1">
                          <input type="checkbox" @click.stop="selectAllport" />
                        </th>
                        <th>
                          名称
                          <i
                            :class="props.filter.orderby == 'name|desc' ? 'el-icon-arrow-up': 'el-icon-arrow-down'"
                            @click="$refs.unselectlist.setOrderby('name')"
                            v-show="0"
                          ></i>
                        </th>
                        <td></td>
                      </tr>
                    </thead>
                  </template>
                  <template slot="item" slot-scope="props">
                    <tr>
                      <td>
                        <input
                          type="checkbox"
                          @change="changeItem(props.item)"
                          v-model="props.item.choose"
                        />
                      </td>
                      <td>
                        <el-popover
                          placement="right"
                          width="530"
                          position="right-start"
                          trigger="click"
                          @show="showimg(props.item)"
                        >
                          <img v-if="imgsrc" :src="imgsrc" alt="流量图" /><span v-else class="font-gray2 f12">处理中, 请稍后...</span>
                          <span style="cursor:pointer" slot="reference">{{props.item.name_cache}}</span>
                        </el-popover>
                      </td>
                      <td>
                        <el-button
                          size="mini"
                          circle
                          icon="el-icon-plus"
                          @click.stop="addone(props.item)"
                        ></el-button>
                      </td>
                    </tr>
                  </template>
                </v-list>
              </div>
              <div class="right-list" v-if="pendingList.length > 0">
                <div class="preselect-box">
                  <el-tag
                    style="margin-right: 5px;margin-bottom: 5px;"
                    v-for="(item, index) in pendingList"
                    :key="index"
                    closable
                    @close="closeTag(item,index)"
                  >{{item.title.substr(0, 50) + '...'}}</el-tag>
                </div>
                <div class="preselect-btns">
                  <el-button style="margin-left:0" size="mini" disabled>已预选: {{ pendingList.length }}</el-button>

                  <el-button style="margin-left:0" size="mini" @click.stop="clearTag">清空</el-button>
                  <el-button style="margin-left:0" size="mini" @click.stop="add">
                    添加
                    <i class="el-icon-arrow-right"></i>
                  </el-button>

                  <el-button
                    style="margin-left:0"
                    size="mini"
                    type="primary"
                    class
                    @click.stop="merge"
                  >
                    合并
                    <i class="el-icon-d-arrow-right"></i>
                  </el-button>
                </div>
              </div>
            </div>
          </div>
          <div class="cl"></div>
        </div>
      </div>
      <div class="tr">
        <div class="dis30"></div>
        <el-form-item label>
          <el-button @click.stop="save" size="big" type="primary">保存</el-button>
          <el-button @click.stop="cancelSubmit" size="big">取消</el-button>
        </el-form-item>
        <div class="dis20"></div>
      </div>
    </el-form>
  </div>
</template>

<script>
import md5 from 'js-md5';
export default {
  props: ["id"],
  data() {
    return {
      emptyNode: '请选择节点',
      emptyHost: '请选择设备',
      keyword: "",
      imgsrc: "",
      nodeId: 0,
      hostId: 0,
      hostName: "",
      hostTitle: "",
      form: {
        id: 0,
        name: "",
        client_id: 0,
        client_name: "",
        bz: "",
        group:0
      },
      formRules: {
        name: [{ required: true, message: "未填写图形名称", trigger: "blur" }]
      },
      data: {id: 0},
      autoHostParams: { node_id: 0, keyword: "" },
      paramsList: {
        orderby: "name|asc",
        node_id: 0,
        host_id: "0",
        keyword: ""
      },
      chooseParseList: [],
      chooseList: [],
      pendingList: [],
    };
  },
  mounted() {
    this.getRow();
  },
  watch: {
    id (val, oldVal) {
      this.getRow()
    }
  },
  methods: {
    onSelGroup(val,key,item){  //选择分组
      this.form.group = item.id
    },
    initForm () {
      this.form.id = this.data.id || 0
      this.form.name = this.data.name || ''
      this.form.client_id = this.data.client_id || 0
      this.form.client_name = this.data.client_name || ''
      this.form.bz = this.data.bz || ''
      this.chooseList = []      
      this.chooseParseList = []
      this.pendingList = []
      if (this.data.items) {
        this.data.items.forEach((item) => {
          this.chooseList.push(item)
        })
      }
      this.parseChoose()
      this.onSelNode(0, '请选择节点')
    },
    getRow () {
      this.$api
        .get("flow_img.get_detail", { id: this.id })
        .then(res => {
          this.data = res.data.img;
          this.data.items = res.data.items
          this.initForm();
        });    
    },
    getIdent (item) {
      return md5(this.hostName + item.name)
    },
    addminsPendlist(item, type) {
      let p = {
        node_id: this.nodeId,
        port_id: item.did,
        name: item.name,
        title: item.name_cache,
        ident: this.getIdent(item),
      }
      let index = -1
      for (let i = 0; i < this.pendingList.length; i++) {
        if (this.pendingList[i]["port_id"] == p["port_id"]) {
          index = i
          break
        }
      }
      if (type === "add") {
        if (index === -1) {
          this.pendingList.push(p);
        }
      } else {
        if (index > -1) {
          this.pendingList.splice(index, 1);
        }
      }
    },
    selectAllport(e) {
      let that = this;
      that.$refs.unselectlist.selAll(e);
      setTimeout(function() {
        let t = that.$refs.unselectlist.fetchSel("did,name_cache");
        if (t.length > 0) {
          t.forEach(item => {
            that.addminsPendlist(item, "add");
          });
        } else {
          t = that.$refs.unselectlist.getData().list;
          t.forEach(item => {
            that.addminsPendlist(item);
          });
        }
      }, 500);
    },
    changeItem(item) {
      if (item.choose) {
        this.addminsPendlist(item, "add");
      } else {
        this.addminsPendlist(item);
      }
    },
    clearTag() {
      this.pendingList = [];
      let t = this.$refs.unselectlist.getData().list;
      t.forEach(item => {
        item.choose = false;
      });
    },
    closeTag(item, index) {
      this.pendingList.splice(index, 1);
      let t = this.$refs.unselectlist.getData().list;
      t.forEach(res => {
        if (item.port_id == res.did) {
          res.choose = false;
        }
      });
    },
    searchHost() {
      //搜索设备
      this.paramsList.keyword = this.keyword;
    },
    showimg (item) {
      var para = {
        port_id: item.port_id || item.did,
        node_id: item.node_id || this.nodeId,
        graph_width: 400,
        graph_height: 80,
        graph_title: item.title || item.name_cache
      }
      this.imgsrc = ""
      if (para["port_id"].indexOf(",") > 0) {
        this.$api.post("cacti.get_merge_port_image", para).then(res => {
          if (res.status === 1) {
            this.imgsrc = res.data;
          }
        })
      } else {
        this.$api.post("cacti.get_port_image", para).then(res => {
          if (res.status === 1) {
            this.imgsrc = res.data;
          }
        })
      }
    },
    cancelSubmit() {
      this.$emit("closeDialog");
    },
    parseChoose () {
      let tmp = {}
      this.chooseList.forEach((item) => {
        if (!tmp[item.md5]) {
          tmp[item.md5] = {
            title: item.title,
            graph_title: item.graph_title,
            node_ids: [{node_id: item.node_id, port_id: item.port_id, title: item.title}],
            md5: item.md5,
            node_id: item.node_id,
            port_id: item.port_id
          }
        } else {
          tmp[item.md5].node_ids.push({node_id: item.node_id, port_id: item.port_id, title: item.title})
        }
      })
      this.chooseParseList = []
      for (let i in tmp) {
        this.chooseParseList.push(tmp[i])
      }
    },
    delParseChoose (index) {
      let md5 = this.chooseParseList[index].md5
      this.chooseList.forEach((item, index) => {
        if (item.md5 == md5) {
          this.chooseList.splice(index, 1)
        }
      })
      this.chooseParseList.splice(index, 1)
    },
    delChoose (index) {
      this.chooseList.splice(index, 1);
    },
    addChoose(portid, MD5, title, graphTitle) {
      let p = {
        port_id: portid,
        node_id: this.nodeId,
        md5: MD5,        
        title: title,
        graph_title: graphTitle
      }
      for (let i = 0; i < this.chooseList.length; i++) {
        if (
          this.chooseList[i]["node_id"] == p["node_id"] &&
          this.chooseList[i]["port_id"] == p["port_id"]
        ) {
          return false;
        }
      }
      this.chooseList.push(p)
      this.parseChoose()
    },
    // 单个添加
    addone (item) {
      this.addChoose(item.did, this.getIdent(item), item.name_cache, item.name_cache);
    },
    // 批量添加已选端口
    add () {      
      this.pendingList.forEach(item => {
        this.addChoose(item.port_id, item.ident, item.title, item.title);
      });
      this.clearTag()
    },
    // 合并已选端口
    merge() {
      if (this.pendingList.length < 2) {
        this.$error("请至少选择两个端口进行合并");
        return;
      }
      let ids = []
      let md5s = []
      this.pendingList.forEach(item => {
        ids.push(item.port_id)
        md5s.push(item.ident)
      });
      // 端口ID 端口 md5
      let port_id = ids.sort().join(',')
      let MD5 = md5(md5s.sort().join(','))
      // 标题
      let title = (this.form.name ? this.form.name : '') + '-' + (this.form.client_name ? this.form.client_name : '') + '-合并端口(' + this.pendingList.length + ')';
      let graphTitle = this.hostTitle + "-MergePort(" + this.pendingList.length + ")";

      let find = false
      for(let i = 0; i < this.chooseParseList.length; i++) {
        if (this.chooseParseList[i].md5 == MD5) {
          title = this.chooseParseList[i].title
          graphTitle = this.chooseParseList[i].graph_title
          find = true
          // 添加到队列
          this.addChoose(port_id, MD5, title, graphTitle);
          this.clearTag()
          break
        }
      }
      // 第一次加相同端口
      if (!find) {
        this.$prompt('请输入合并端口名', '', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValidator: /\w+?/,
          inputErrorMessage: '合并端口名格式不正确',
          inputValue: title
        }).then(({ value }) => {
          if (value != '') {
            title = value
            graphTitle = value
          }
          // 添加到队列
          this.addChoose(port_id, MD5, title, graphTitle);
          this.clearTag()    
        }).catch(() => {  
        });
      }         
    },
    // 选择客户
    onSelClient(key, value, item) {
      let that = this;
      that.form.client_id = key;
      that.form.client_name = value;
    },
    // 保存
    save() {
      let that = this;
      that.$refs["form"].validate(valid => {
        //验证前面的表单是否符合要求
        if (valid) {
          let url = that.form.id ? "flow_img.update_img" : "flow_img.save_img";
          that.status = true;
          that.form.data = that.chooseList
          that.$api.post(url, that.form).then(res => {
            if (res.status === 1) {
              this.getRow()
              this.$success(res.msg)
              this.$emit("closeDialog")
            } else {
              that.$error(res.msg);
            }
            that.status = false;
          });
        }
      });
    },    
    // 节点和设备下拉框
    onSelNode(val, key, item) {
      this.pendingList = [];
      this.emptyNode = key
      this.nodeId = parseInt(val)
      this.$set(this.autoHostParams, "node_id", this.nodeId);
      this.$set(this.paramsList, "node_id", this.nodeId);
      // this.onSelHost(0, '请选择设备', {description: ''})
      this.$api.get('cacti.refresh_host',{'node_id':parseInt(val)}).then(res => {
        if(res.status == 1){
        }else{
          this.$error('设备缓存清除失败')
        }
      })
    },
    onSelHost(val, key, item) {
      this.hostId = parseInt(val)
      this.emptyHost = key
      this.$set(this.paramsList, "host_id", this.hostId)
      this.$set(this.paramsList, "keyword", this.keyword)
      this.hostTitle = item.description
      this.hostName = item.hostname
    }
  }
};
</script>

<style lang="scss" scoped>
.edit-graph-box {
}
.edit-graph-box h1 {
  font-weight: 400;
  font-size: 16px;
  height: 48px;
  line-height: 48px;
  padding: 0 0px;
  background-color: #f8f8f8;
  border-bottom: solid 1px #efefef;
}
.edit-graph-box h1 span.title {
  display: inline-block;
  color: #3860f4;
  border-bottom: solid 2px #3860f4;
  padding: 0 12px;
}
.sel-graph-box {
  background-color: #efefef;
}
.selected-box {
  width: 30%;
  float: right;
  height: 500px;
  border: solid 1px #ccc;
  background-color: #fff;
  position: relative;
}
.selected-box .select-list-box {
  background: #fff;
  position: absolute;
  bottom: 38px;
  top: 0;
  left: 0;
  right: 0px;
  overflow-y: auto;
}
.selected-box .vbtns {
  background: #fff;
  position: absolute;
  bottom: 0px;
  left: 0;
  right: 0px;
  text-align: center;
  line-height: 38px;
  height: 38px;
  border-top: solid 1px #efefef;
}
.unselect-box {
  width: 69%;
  float: left;
  height: 500px;
  border: solid 1px #efefef;
  position: relative;
  background-color: #fff;
}
.opbtn-box {
  padding-top: 120px;
  float: right;
  width: 7%;
  text-align: center;
}
.unselect-box .filter-box {
  height: 48px;
  padding: 0 24px;
  background-color: #f1f1f1;
  line-height: 48px;
}
.unselect-box .left-list {
  position: absolute;
  top: 48px;
  left: 0;
  right: 0;
  bottom: 0px;
  overflow-y: auto;
}
.unselect-box .right-list {
  position: absolute;
  top: 48px;
  right: 0px;
  bottom: 0px;
  width: 38%;
  border-left: solid 1px #efefef;
}
.unselect-box .right-list .preselect-box {
  overflow-x: hidden;
  overflow-y: auto;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 38px;
  left: 0px;
  padding: 12px;
}
.unselect-box .right-list .preselect-btns {
  text-align: center;
  position: absolute;
  bottom: 0;
  right: 0;
  left: 0;
  height: 38px;
  border-top: solid 1px #efefef;
  line-height: 38px;
}
</style>
